import { getSignature, initUser, agentsignature } from '@/config/api'
import { invokeWX } from '@/util/wxConfig.js'
export default {
  data() {
    return {
      agentid: '1000051', //启晁
      appid: 'ww7b2aa4df9044d73e',
      // agentid: '1000006',  //知音眼镜
      // appid: "ww200eba22d7a52732",
      userId: null,
    }
  },
  async onLoad() {
    if (
      window.location.href.indexOf('code') >= 0 &&
      !uni.getStorageSync('UserId')
    ) {
      await this.getParams(window.location.href)
    }
  },
  methods: {
    async getUserInfo(obj) {
      let res = await initUser({
        code: obj.code,
      })
      this.userId = res.userid
      uni.setStorageSync('UserId', res.userid)
      window.location.href = ''
    },
    async getParams(url) {
      let that = this
      return new Promise((resolve, reject) => {
        var params = url.split('?')[1]
        if (!params) return null
        var arr = params.split('&')
        var o = {}
        for (var i = 0; i < arr.length; i++) {
          var tmpArr = arr[i].split('=')
          var key = tmpArr[0]
          var value = tmpArr[1]
          o[key] = value
        }
        initUser({
          code: o.code,
        }).then((res) => {
          uni.setStorageSync('UserId', res.userid)
          resolve()
        })
      })
    },
    // 获取
    async initSignature(data, source) {
      console.log(window.location)
      let that = this
      return new Promise(async (resolve, reject) => {
        // let res = await getSignature({
        // 	url: 'https://' + window.location.host + '/dist/'
        // });
        // let agent = await agentsignature({
        // 	url: 'https://' + window.location.host + '/dist/'
        // })
        let url = window.location.href.split('#')[0]
        let res = await getSignature({
          url,
        })
        let agent = await agentsignature({
          url,
        })
        let resdata = res,
          agentObj = agent
        resdata.appId = that.appid
        resdata.agentid = that.agentid
        resdata.corpid = that.appid

        agentObj.appId = that.appid
        agentObj.agentid = that.agentid
        agentObj.corpid = that.appid
        await invokeWX(resdata, agentObj, that)
        resolve()
      })

      resdata.appId = this.appid
      resdata.agentid = this.agentid
      resdata.corpid = this.appid
      if (source === 'chat') {
        this.userId =
          window.sessionStorage.getItem('userId') || (await invokeWX(resdata)) // 获取外部联系人ID
      }
      if (source === 'group_chat') {
        this.groupId =
          window.sessionStorage.getItem('chatId') || (await invokeWX(resdata)) // 获取外部群聊ID
      }
      return source === 'chat' ? this.userId : this.groupId
    },
    //发消息
  },
}
